<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { postAddService, updatePostService } from '@/api/post'
import { useUserStore } from '@/stores';
import { clearForm } from '@/utils/utils'

const userStore = useUserStore()
const drawer = ref(false)
const cancelClick = () => {
    drawer.value = false
}

const emit = defineEmits(['update'])
const confirmClick = async () => {
    drawer.value = false

    if (form.id.length === 0) {
        form.username = userStore.user.username
        const { data } = await postAddService(form)
        ElMessage.success(data.message)
    } else {
        const { data } = await updatePostService(form)
        ElMessage.success(data.message)
    }
    clearForm(form)
    emit('update')
}

const form: any = reactive({
    id: '',
    title: '',
    content: '',
    username: '',
    time: ''
})
const open = (post: any = null) => {
    drawer.value = true
    if (post) {
        Object.keys(form).forEach(key => {
            if (post[key] !== null && post[key] !== undefined) {
                form[key] = post[key]
            }
        })

    }
}
defineExpose(
    { open }
)
</script>
<template>
    <el-drawer v-model="drawer" direction="rtl">
        <template #header>
            <div class="header">
                <el-text type="success" v-if="form.id">更新Post</el-text>
                <el-text type="primary" v-else>发布Post</el-text>
            </div>
        </template>
        <template #default>
            <div>
                <el-form :model="form" label-width="auto">
                    <el-form-item>
                        <template #label><el-text type="primary">Title: </el-text></template>
                        <el-input v-model="form.title" maxlength="60" show-word-limit />
                    </el-form-item>
                    <el-form-item>
                        <template #label><el-text type="primary">Content: </el-text></template>
                        <el-input v-model="form.content" :autosize="{ minRows: 10, maxRows: 50 }" type="textarea"
                            resize="none" />
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelClick">cancel</el-button>
                <el-button type="primary" @click="confirmClick">confirm</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<style lang="scss" scoped>
.el-drawer {
    .header {
        .el-text {
            font-size: 24px;
            font-family: 'Times New Roman', Times, serif;
        }
    }

    .el-form {
        max-width: 500px;

        .el-form-item {
            .el-text {
                font-size: 16px;
                font-family: 'Times New Roman', Times, serif;
            }

            .el-input {
                width: 90%;
            }
        }

    }
}
</style>